$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

$(document).ready(function () {
    var projectUserList =  {};//角色

	var requestId= $('#requestId').val();
   var colModel = [
        {
            label: '物料代码',
            name: 'materialNo',
            index: 'MATERIAL_NO',
            width: 80,
        },
        {
            label: '物料名称',
            name: 'materialName',
            index: 'MATERIAL_NAME',
            width: 80,
        },
        {
            label: '型号规格',
            name: 'character',
            index: 'CHARACTER',
            width: 80
        },
        {
            label: '生产厂家（品牌）',
            name: 'producer',
            index: 'PRODUCER',
            width: 80,
        },
        {
            label: '采购数量',
            name: 'requestAmount',
            index: 'REQUEST_AMOUNT',
            width: 80
        },
        {
            label: '计量单位',
            name: 'unit',
            index: 'UNIT',
            width: 80
        },
        {
            label: '参考单价（元）',
            name: 'salePrice',
            index: 'SALE_PRICE',
            width: 80,
        },
        {
            label: '交货期',
            name: 'requestDeliveryDate',
            index: 'REQUEST_DELIVERY_DATE',
            width: 80,
            formatter:'date',
            formatoptions:{srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d'}
        },
        {
            label: '备注',
            name: 'memo',
            index: 'MEMO',
            width: 80,
        }
    ];
    $.post(ctx+'/rfqRequest/getCustomItemHeader',{"requestId":requestId}, function (data) {
        $.each(data.obj, function (i, item) {
            var res = {};
            res.label = item.itemName;
            res.name = "itemValue_" + (i + 1);
            res.width = 80;
            colModel.push(res);
        });
        RFQ.jqGrid("#jqGrid").init({
            url: ctx + '/rfqRequest/rfqRequestItemList',
            colModel: colModel,
            postData: {"id": requestId},
            width: 980,
            sortname: 'SEQ',
            sortorder: 'ASC',
            pager: "#jqGridPager",
            rowNum: 20,//每页显示记录数
            rowList: [20, 30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
        });
    });
	$("#jqGrid").jqGrid('resizeGrid');


    var isSupplierRequirement = $("#isSupplierRequirement").val();
    if (isSupplierRequirement == '0') {
        $("#supplierListJqGrid").jqGrid({
            datatype: 'local',
            rownumbers: true,
            rownumWidth: 50,
            colModel: [
                {
                    label: 'id',
                    name: 'id',
                    index: 'id',
                    key: true,
                    hidden: true
                },
                {
                    label: '供应商U代码',
                    name: 'supplierCode',
                    index: 'supplierCode',
                    align: 'center'
                },
                {
                    label: '特邀供应商名称',
                    name: 'supplierName',
                    index: 'supplierName',
                    align: 'center'
                },
                {
                    label: '联系人',
                    name: 'linkmanName',
                    index: 'linkmanName',
                    align: 'center'
                },
                {
                    label: '联系电话',
                    name: 'linkmanTelphone',
                    index: 'linkmanTelphone',
                    align: 'center'
                    // formatter: lockChangeFormatter
                },
                {
                    label: '微信状态',
                    name: 'isBindWechat',
                    index: 'isBindWechat',
                    align: 'center'
                    // formatter: lockChangeFormatter
                }
            ],
            viewrecords: true,
            //sortname: 'userLoginNo',
            //sortorder: 'asc',
            width: "970",
            height: "100%",
            pager: "#supplierListjqGridPager",
            rowNum: 20,//每页显示记录数
            rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
        });
    } else if (isSupplierRequirement == '1') {
        $("#supplierListJqGrid").jqGrid({
            datatype: 'local',
            rownumbers: true,
            rownumWidth: 50,
            colModel: [
                {
                    label: 'id',
                    name: 'id',
                    index: 'id',
                    key: true,
                    hidden: true
                },
                {
                    label: '供应商U代码',
                    name: 'supplierCode',
                    index: 'supplierCode',
                    align: 'center'
                },
                {
                    label: '特邀供应商名称',
                    name: 'supplierName',
                    index: 'supplierName',
                    align: 'center'
                },
                {
                    label: '联系人',
                    name: 'linkmanName',
                    index: 'linkmanName',
                    align: 'center'
                },
                {
                    label: '联系电话',
                    name: 'linkmanTelphone',
                    index: 'linkmanTelphone',
                    align: 'center'
                    // formatter: lockChangeFormatter
                },
                {
                    label: '微信状态',
                    name: 'isBindWechat',
                    index: 'isBindWechat',
                    align: 'center'
                    // formatter: lockChangeFormatter
                }
            ],
            viewrecords: true,
            //sortname: 'userLoginNo',
            //sortorder: 'asc',
            width: "970",
            height: "100%",
            pager: "#supplierListjqGridPager",
            rowNum: 20,//每页显示记录数
            rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
        });
    }
    $("#supplierListJqGrid").jqGrid('setLabel', 0, "序号");
    if (isSupplierRequirement == '0') {

        var supplierList = JSON.parse($("#supplierList").val());
        if (supplierList != undefined && supplierList != null) {

            $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierList}).trigger('reloadGrid');
        }
        //debugger;
    } else if (isSupplierRequirement == '1') {


        var preauditSupplierList = JSON.parse($("#preauditSupplierList").val());
        if (preauditSupplierList != undefined && preauditSupplierList != null) {

            $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: preauditSupplierList}).trigger('reloadGrid');
        }
    }

	//表单提交(发布)
	(function(){
		var $myModa6 = $('#myModa6');
		//表单操作按钮
		$('#Myform').on('click','.js-form-btn',function(){
			var $this = $(this);
			$('#Myform').ajaxSubmit({
				type: 'post', // 提交方式 get/post
				url: ctx+'/rfqRequest/RequestRelease', // 需要提交的 url
				dataType: 'json',
				success: function (data) {
					if(data.rspcod != 200){
						RFQ.error(data.rspmsg);
						return;
					}else{
						RFQ.info(data.rspmsg);
						location.href=ctx+"/rfqRequest/init";
					}
				RFQ.renderText('#myModa6',data.obj);
				$myModa6.data('id',data.obj.requestId);
				$myModa6.modal('show');
				},
				error : function(XmlHttpRequest, textStatus, errorThrown){
					RFQ.error('出错了！');
				}
			});
		});
	})();
	//END

    //表单提交(调整时间)
    (function(){
        var $adjustTime = $('#adjustTime');
        //表单操作按钮
        $('#adjustTime_form').on('click','.save_Time',function(){
            var quotationStartDate=$('#quotationStartDate').val();
            var quotationEndDate=$('#quotationEndDate').val();
            if(quotationStartDate>quotationEndDate){
                RFQ.error('报价结束时间要大于报价开始时间');
                return false;
            }
            $('#adjustTime_form').ajaxSubmit({
                type: 'post', // 提交方式 get/post
                url: ctx+'/rfqRequest/RequestadjustTime', // 需要提交的 url
                dataType: 'json',
                success: function (data) {
                    if(data.rspcod != 200){
                        RFQ.error(data.rspmsg);
                        return;
                    }else{
                        location.href=ctx+"/rfqRequest/rfqRequestRelease?id="+data.rspmsg;
                    }
                },
                error : function(XmlHttpRequest, textStatus, errorThrown){
                    RFQ.error('出错了！');
                }
            });
        });
    })();
    //END


    //角色设置
    (function(){
        var jqGrid = null;
        var roleData = [];
        var $myModaphone = $('#myModaphone');
        var $form = $myModaphone.find('form');
        $myModaphone.on('shown.zui.modal',function(){
            getAttData("#jqGridphone","#jqGridPagerphone");
        });

        function getAttData(grid,page){
            jqGrid = RFQ.jqGrid(grid).init({
                datatype:"local",
                multiselect: true,
                colModel: [
                    {
                        label: '主键',
                        name: 'userId',
                        width: 20,
                        key: true,
                        hidden: true
                    },
                    {
                        label: '工号',
                        name: 'jobCode',
                        width: 20,
                    },
                    {
                        label: '姓名',
                        name: 'userName',
                        width: 20,
                    },
                    {
                        label: '所属科室',
                        name: 'userOffice',
                        width: 20,
                    },
                    {
                        label: '职位',
                        name: 'userTitle',
                        width: 20
                    }
                ],
                pager: page
            });
            $.post(ctx+ '/rfqProjectUserNew/rfqProjectUserListNew',{}, function (data) {
                roleData = (data.list||[]).filter(function (item) {
                    return !projectUserList[item.userId];
                });
                $form[0].reset();
                $.placeholder();
                jqGrid.loadLocal(roleData);
            },'json');
        }

        $("#roleSearch").click(function () {
            var validJson = {};
            $form.find(':text,select').each(function () {
                this.value && (validJson[this.name] = this.value);
            });
            var searchData = roleData.filter(function (item) {
                var isValid = true;
                for(var key in validJson){
                    if(!isValid) return false;
                    //if(key == 'userOffice' || key == 'userName'){
                        if(item[key] != null){
                            isValid = ~item[key].indexOf(validJson[key]);//模糊匹配
                        }else{
                            return false;
                        }

                    //}else{
                    //    isValid = (item[key] == validJson[key]);
                    //}
                }
                return isValid;
            });
            jqGrid.loadLocal(searchData);
        });

        //DOM操作
        var rowIndex = 0;
        var rowTmp = '<tr id="puser_{userId}"> <td>{index}</td> <td>{jobCode}</td> <td>{userName}</td> <td>{userOffice}</td> <td>{userTitle}</td> <td><input name="" type="checkbox"></td> <td><input name=""  type="checkbox"></td> <td><input name="" type="checkbox"></td> <td><a class="text-danger order-del-btn" data-id="{userId}"><i class="icon icon-trash"></i>&nbsp; 删除</a></td> </tr>';

        //if(module == 'edit'){
        //当前存在的数据加入缓存
        $('#roleSetTable tbody').find('tr').each(function () {
            var tmp = {};
            $(this).find('td').each(function () {
                var $this = $(this);
                var name = $this.data('name');
                if(!name) return true;
                tmp[name] = $this.data('value');
            });
            projectUserList[tmp.userId] = tmp;
            rowIndex ++;
        });
        //}
        RFQ.d(projectUserList);

        $('#myModaphone').on('click','.js-confirm', function () {
            var rows = $('#jqGridphone').jqGrid("getGridParam", "selarrrow");
            var renderHTML = [];
            $.each(rows,function(i,r){
                if(projectUserList[r]) return true;
                var rowData = $('#jqGridphone').jqGrid('getRowData',r);//获取选中行的数据（单行）
                rowData.index = rowIndex + 1;
                renderHTML.push(rowTmp.format(rowData));
                rowIndex ++;
                projectUserList[r] = rowData;
            });
            $('#roleSetTable tbody').append(renderHTML.join(''));
            $('#myModaphone').modal('hide');
            resetSeq();
            RFQ.d(projectUserList);
        });

        //表单操作按钮
        $('#role_form').on('click','.save_role',function(){
            var extras = fecthExtraParams();
            $('#role_form').ajaxSubmit({
                type: 'post', // 提交方式 get/post
                url: ctx+'/rfqRequest/RequestadjustRole', // 需要提交的 url
                dataType: 'json',
                data:extras,
                success: function (data) {
                    if(data.rspcod != 200){
                        RFQ.error(data.rspmsg);
                        return;
                    }else{
                        location.href=ctx+"/rfqRequest/rfqRequestRelease?id="+data.rspmsg;
                    }
                },
                error : function(XmlHttpRequest, textStatus, errorThrown){
                    RFQ.error('出错了！');
                }
            });
        });


        //删除
        $('#roleSetTable').on('click','.order-del-btn',function(){
            var id = $(this).data("id");
            $(this).parent().parent("tr").remove();
            delete projectUserList[id];
            rowIndex >0 && rowIndex--;
            resetSeq();
            RFQ.d(projectUserList);
        });

        //重新设置序号
        function resetSeq(){
            var $tds = $('#roleSetTable tbody').find('tr td:first-child');
            $tds.each(function (i,el) {
                $(this).html(i+1);
            });
        }
        //抓取额外参数
        function fecthExtraParams(){
            //组装额外参数 选取的供应商以及角色
            var extras = {};
            if(!$.isEmptyObject(projectUserList)){
                var index = 0,tmp;
                for(var key in projectUserList){
                    tmp = projectUserList[key];
                    extras['projectUserList['+index+'].seq'] = index+1;
                    extras['projectUserList['+index+'].userId'] = tmp.userId;
                    extras['projectUserList['+index+'].userOffice'] = tmp.userOffice;
                    extras['projectUserList['+index+'].jobCode'] = tmp.jobCode;
                    extras['projectUserList['+index+'].userName'] = tmp.userName;
                    extras['projectUserList['+index+'].userTitle'] = tmp.userTitle;
                    //获取选中的权限
                    var $checks = $('#puser_' + key).find(':checkbox');
                    extras['projectUserList['+index+'].viewQx'] = $checks.eq(0).prop('checked')?1:0;
                    extras['projectUserList['+index+'].optionQx'] = $checks.eq(1).prop('checked')?1:0;
                    extras['projectUserList['+index+'].caiwuQx'] =  $checks.eq(2).prop('checked')?1:0;
                    index++;
                }
            }
            return extras;
        }


    })();
    //END

});